package Controller.User;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 图片验证码的获取,并且将验证码存入session中
* */
@WebServlet(name = "captchaCreate", value = "/CaptchaCreate")
public class CaptchaCreate extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建一个验证码图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200,100);
        //获取当前验证码表示的信息打印到控制台(idea里的)
        String code=lineCaptcha.getCode();
        System.out.println("验证码:"+code);
        //将验证码存入session中(后面要比较输入的验证码是否正确)
        request.getSession().setAttribute("captchaCode",code);
        //图片名称
        String imgName=System.currentTimeMillis()+".png";
        //告知客户端进行图片下载
        response.setHeader("content-type","image/png");
        response.setHeader("Content-Disposition","attachment;filename="+imgName);

        //创建字节输出流
        ServletOutputStream servletOutputStream=response.getOutputStream();
        //将图片输出到客户端页面上
        lineCaptcha.write(servletOutputStream);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
